//
//  AppStartUpConfig.m
//  industry
//
//  Created by xl on 2020/11/11.
//  Copyright © 2020 Haier. All rights reserved.
//

#import "AppStartUpConfig.h"
#import "XLBaseNavigationController.h"
#import "AppDelegate.h"
#import "ZYNetworkAccessibity.h"
#import "AppUIConfig.h"
#import "XLUserDefaults.h"
#import "XLNetworking.h"
#import "XLLoginRegisterVC.h"
#import <IQKeyboardManager/IQKeyboardManager.h>
#import "XLPushTool.h"
#import "XLSafeLoginAlertView.h"
#import "YQChangeHomeVC.h"



@interface AppStartUpConfig ()

@property (nonatomic, strong) AppUIConfig *uiConfig;
@property (nonatomic, strong) XLPushTool *pushTool;
@property (nonatomic, strong) XLSafeLoginAlertView *safeAlertView;

@property (nonatomic, assign) BOOL isActive;


@end
@implementation AppStartUpConfig
XLShareInstance_implementation(AppStartUpConfig)

- (instancetype)init {
    self = [super init];
    if (self) {
        [XLNotif addObserver:self selector:@selector(tokenDisable:) name:XLNotificationTokenDisableFromServer object:nil];
        
        [XLNotif addObserver:self selector:@selector(willEnterForeground) name:UIApplicationWillEnterForegroundNotification object:nil];
        [XLNotif addObserver:self selector:@selector(didBecomeEnterBackground) name:UIApplicationDidEnterBackgroundNotification object:nil];
        _isStaff = true;
    }
    return self;
}

- (void)configAppWithApplication:(UIApplication *)application
                   launchOptions:(NSDictionary *)launchOptions {
    UIWindow *window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    YQChangeHomeVC * changeHomeVC = [[YQChangeHomeVC alloc]init];
    window.rootViewController = [[XLBaseNavigationController alloc] initWithRootViewController:changeHomeVC];
    [AppDelegate sharedInstance].window = window;
    [AppDelegate sharedInstance].navigationController = (XLBaseNavigationController *)window.rootViewController;
    [window makeKeyAndVisible];
    window.backgroundColor = [UIColor whiteColor];
    [[DTFrameworkInterface sharedInstance] manualInitMpaasFrameworkWithApplication:application launchOptions:launchOptions];
    
    if (XLLogEnable) {
        [XLAppLog setLogEnable:YES];
    } else {
        [XLAppLog setLogEnable:NO];
    }
//    [WXApi startLogByLevel:WXLogLevelDetail logBlock:^(NSString *log) {
//        NSLog(@"WeChatSDK: %@", log);
//    }];
    //向微信注册
        [WXApi registerApp:WXAPP_ID universalLink:UNIVERSAL_LINK];
    
    NSString *token = [XLUserDefaults getLastAvailableToken];
    [XLNetworking updateCustomHeaderDicWithToken:token];
    
    // 判断网络权限
    [ZYNetworkAccessibity start];
    
    //配置消息推送
    [self.pushTool configXLPush];
    
    //设置IQ键盘
    [self keyBoardConfig];
    
    //设置UI整体样式
    [self.uiConfig configUI];
    
    //直接进入首页
    [self jumpMainControllerWithVC:nil];
}

/// 切换视图控制器
- (void)changeRootViewContorller:(BOOL)isStaff{
    
    for (UIViewController *controller in [AppDelegate sharedInstance].navigationController.viewControllers) {
        if ([controller isKindOfClass:[YQChangeHomeVC class]]) {
            [[AppDelegate sharedInstance].navigationController popToViewController:controller animated:NO];
            YQChangeHomeVC *changeVC = (YQChangeHomeVC *)controller;
            [changeVC changeViewContorller:isStaff];
        }
    }

}

- (void)setIsStaff:(BOOL)isStaff{
    if (self.isStaff != isStaff) {
        _isStaff = isStaff;
            
        [self changeRootViewContorller:isStaff];

    }
    
}

#pragma mark - Public
- (void)jumpMainControllerWithVC:(XLBaseViewController *)controller {
    if (controller != nil) {
        [controller dismissViewControllerAnimated:YES completion:^{
            [controller.navigationController popToRootViewControllerAnimated:NO];
        }];
        //登录进来的
    } else {
        if (XL_UserInfoData != nil) {
            //用户已经登录了，token没有失效
            self.isActive = YES;
            [self willEnterForeground];
            [XLNotif postNotificationName:XLNotificationUserLoginSuccess object:nil];
        } else {
            //用户信息为空
            [self jumpLoginRegsiterControllerWithVC:(XLBaseViewController *)self.currentTopController];
        }
    }
}

- (void)jumpLoginRegsiterControllerWithVC:(XLBaseViewController *)controller {
    if ([controller isKindOfClass: [XLLoginRegisterVC class]] || [self.currentTopController isKindOfClass:[XLLoginRegisterVC class]]) {
        return;//当前已经在登录不需要再弹出登录页
    }
    
    [[XLPushTool sharedXLPushTool] unbindXLIdentifier];
    [[XLUserData sharedXLUserData] saveCurrentUserInfo:nil];

    XLLoginRegisterVC *loginRegisterController = [[XLLoginRegisterVC alloc] init];
    XLBaseNavigationController *navigationController = [[XLBaseNavigationController alloc] initWithRootViewController:loginRegisterController];
    [[AppDelegate sharedInstance].navigationController presentViewController:navigationController animated:YES completion:^{
        for (UIViewController *controller in [AppDelegate sharedInstance].navigationController.viewControllers) {
            if ([controller isKindOfClass:[YQChangeHomeVC class]]) {
                [[AppDelegate sharedInstance].navigationController popToViewController:controller animated:NO];
                YQChangeHomeVC *tabbarVC = (YQChangeHomeVC *)controller;
                [tabbarVC InterfaceInit];
            }
        }

     }];
}

#pragma mark - IQKeyBoard
- (void)keyBoardConfig {
    IQKeyboardManager *manager = [IQKeyboardManager sharedManager];
    manager.enable = YES;
    manager.shouldResignOnTouchOutside = YES;
    manager.enableAutoToolbar = NO;//不显示toolBar
}

#pragma mark - Notif
- (void)tokenDisable:(NSNotification *)notif
{
    [XLToast showComonMessage:@"登录验证失效，请重新登录！"];
    [self jumpLoginRegsiterControllerWithVC:(XLBaseViewController *)self.currentTopController];
}

- (void)willEnterForeground {
    if (self.isActive) {
        if ([self.currentTopController isKindOfClass:[XLLoginRegisterVC class]] || XL_UserInfoData == nil) {
            return;
        }
        NSInteger type = [XLUserDefaults getLastLoginWay];
        if (type == XLLoginWayTypeBrushFaceUnlock ||
            type == XLLoginWayTypeFingerprintUnlock ||
            type == XLLoginWayTypePasswordUnlock ||
            type == XLLoginWayTypeGestureUnlock) {//刷脸.指纹.数字密码.手势密码
            _isActive = NO;
            [self.safeAlertView showSafeLoginView:type];
            [_safeAlertView loadLoginSuccessBlock:^{
                XLLog(@"成功");
                self->_isActive = YES;
            } failBlock:^{
                XLLog(@"失败");
            }];
            WEAKSELF
            _safeAlertView.exitBlock = ^{
                STRONGSELF
                 //退回到登录界面
                 [strongSelf jumpLoginRegsiterControllerWithVC:(XLBaseViewController *)strongSelf.currentTopController];
             };
        }
    }
}

- (void)didBecomeEnterBackground {
    self.isActive = YES;
}

#pragma mark - setter/getter
- (AppUIConfig *)uiConfig {
    if (!_uiConfig) {
        _uiConfig = [AppUIConfig new];
    }
    return _uiConfig;
}

- (XLPushTool *)pushTool {
    if (!_pushTool) {
        _pushTool = [XLPushTool new];
    }
    return _pushTool;
}

- (XLSafeLoginAlertView *)safeAlertView {
    if (!_safeAlertView) {
        _safeAlertView = [[XLSafeLoginAlertView alloc] init];
    }
    return _safeAlertView;
}

@end
